package com.rich.web.servlet;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import com.rich.constant.Constant;
import com.rich.domain.Category;
import com.rich.domain.Product;
import com.rich.service.ProductServer;
import com.rich.utils.BeanFactory;
import com.rich.utils.UUIDUtils;
import com.rich.utils.UploadUtils;

/**
 * Servlet implementation class AddProductServlet
 */
@WebServlet("/addProduct")
public class AddProductServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	ProductServer ps = (ProductServer) BeanFactory.getBean("ProductService");

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("adsasd");
		try {
			//创建map
			Map<String, Object> map = new HashMap<>();
			//获取上传表单数据
			//1.获取磁盘文件工厂
			DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
			//2创建核心上传对象
			ServletFileUpload fileUpload = new ServletFileUpload(diskFileItemFactory);
			//3解析数据
			List<FileItem> list = fileUpload.parseRequest(request);
			//4遍历，获取每一个文件项
			for (FileItem fileItem : list) {
				//4.1获取name属性
				String key = fileItem.getFieldName();
				//4.2判断是否是普通上传组件
				if(fileItem.isFormField()) {
					//普通
					map.put(key, fileItem.getString("utf-8"));
				}else {
					//文件
					//1获取文件名称
					String name = fileItem.getName();
					//2获取文件真实名称
					String realName = UploadUtils.getRealName(name);
					//3获取文件随机名称
					String uuidName = UploadUtils.getUUIDName(realName);
					//4获取随机目录
					String dir = UploadUtils.getDir();
					//5获取文件内容 
					InputStream in = fileItem.getInputStream();
					//6创建输出流
					//6.1设置输出流保存路径:项目根目录/products
					//String productPath = getServletContext().getRealPath("/products");
					String productPath = "C:\\JAVA\\code\\Store\\WebContent\\products";
					//6.2在/products下创建随机目录
					File dirfile = new File(productPath, dir);
					//6.3判断是否有这个目录
					if(!dirfile.exists()) {
						dirfile.mkdirs();
					}
					//6.4输出流
					FileOutputStream out = new FileOutputStream(new File(dirfile,uuidName));
					//7拷贝流
					IOUtils.copy(in, out);
					//释放资源
					in.close();
					out.close();
					//9删除临时文件
					fileItem.delete();
					//10将商品图片的保存map,保存到mysql中的路径为相对项目路径，拼接
					//map.put(key, "products"+dir+"/"+uuidName);//如：pruducts/1/4/123123.jpg
					map.put(key, "C:\\JAVA\\code\\Store\\WebContent\\products"+dir+"/"+uuidName);
				}
			}
			//封装product对象
			//1.手动设置数据库中有，但表单中没有的字段
			Product p = new Product();
			map.put("pid", UUIDUtils.getId());
			map.put("pflag", Constant.PRODUCT_IS_UP);
			map.put("pdate", new Date());
			BeanUtils.populate(p, map);
			//手动封装category的cid
			Category c = new Category();
			c.setcID((String)map.get("cid"));
			p.setCategory(c);
			
			//调用sercice
			ps.save(p);
			//重定向[=
			response.sendRedirect(request.getContextPath()+"/adminProduct?method=findAll");
		} catch (Exception e) {
			e.printStackTrace();
			throw new RuntimeException("添加商品失败");
		}
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);  
	}

}
